package com.imooc.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.imooc.base.BaseInfoProperties;
import com.imooc.exceptions.GraceException;
import com.imooc.grace.result.ResponseStatusEnum;
import com.imooc.mapper.AdminMapper;
import com.imooc.pojo.Admin;
import com.imooc.pojo.BO.CreateAdminBO;
import com.imooc.pojo.VO.AdminVO;
import com.imooc.service.AdminService;
import com.imooc.utils.MD5Utils;
import com.imooc.utils.PagedGridResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 慕聘网运营管理系统的admin账户表，仅登录，不提供注册 服务实现类
 * </p>
 *
 * @author 风间影月
 * @since 2025-03-21
 */
@Service
public class AdminServiceImpl extends BaseInfoProperties implements AdminService {


    @Autowired
    private AdminMapper adminMapper;


    @Override
    public void createAdmin(CreateAdminBO createAdminBO) {

        Admin admin = getSelfAdmin(createAdminBO.getUsername());
        if (admin != null)
            GraceException.display(ResponseStatusEnum.ADMIN_USERNAME_EXIST_ERROR);

        Admin newAdmin = new Admin();
        BeanUtils.copyProperties(createAdminBO, newAdmin);

        // 生成随机盐
        String slat = (int) ((Math.random() * 9 + 1) * 100000) + "";
        String pwd = MD5Utils.encrypt(createAdminBO.getPassword(), slat);
        newAdmin.setPassword(pwd);
        newAdmin.setSlat(slat);

        newAdmin.setCreateTime(LocalDateTime.now());
        newAdmin.setUpdatedTime(LocalDateTime.now());

        adminMapper.insert(newAdmin);
    }

    @Override
    public PagedGridResult getAdminList(String accountName, Integer page, Integer limit) {

        PageHelper.startPage(page, limit);

        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(accountName)) {
            wrapper.like("username", accountName);
        }
        List<Admin> adminList = adminMapper.selectList(wrapper);

        List<AdminVO> adminVOList = new ArrayList<>();

        for (Admin admin : adminList) {
            AdminVO adminVO = new AdminVO();
            BeanUtils.copyProperties(admin, adminVO);
            adminVOList.add(adminVO);
        }

        return setterPagedGrid(adminVOList, page);
    }

    @Override
    public void deleteAdmin(String userName) {
        if (!Objects.equals(userName, "admin")) {
            adminMapper.delete(new QueryWrapper<Admin>().eq("username", userName));
        } else {
            GraceException.display(ResponseStatusEnum.ADMIN_DELETE_ERROR);
        }
    }

    private Admin getSelfAdmin(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
    }
}
